// /pages/room/room.js
const app = getApp();
const Second = require('../../utils/time');
const util = require('../../utils/util');
Page({
  data: {
    MusicFromData: [],//播放列表
    roomText: '',//房间标题
    isPlaying: true,
    curtime: 0,
    durtime: 0,
    jindu: 0,
    play_music: '',//播放链接
    PlayingImage: '',
    PlayListVisible: false,
    albumMid:'',
    lyrics: [],
    currentTimeStamp: 0,

    ImagePlay: '/static/播放.png',

  },

  onLoad(options) {
    let isPlaying = wx.getStorageSync('MusicFromData');
    let NowTime = wx.getStorageSync('currentTime');
    // console.log(isPlaying);
    this.setData({
      MusicFromData: isPlaying,
      currentTimeStamp: NowTime
    });
    app.globalData.backgroundAudioManager = wx.getBackgroundAudioManager();
    // console.log(this.data.currentTimeStamp);
    this.LoadPlayList();
    
    this.getRoomSongTime();
    this.loadSong();


  },

  onShow() {
    this.setData({
      MusicFromData: wx.getStorageSync('MusicFromData')
    });
    this.getRoomSongTime();
    this.loadSong();
    
  },

  onUnload() {
    app.globalData.backgroundAudioManager.stop();
    this.stopUpdateInterval();
  },

  OpenPlayList: function () {
    this.setData({
      PlayListVisible: true,
      MusicFromData: this.data.MusicFromData
    });
  },
  ClosePlayList: function () {
    this.setData({
      PlayListVisible: false
    });
  },
  stopUpdateInterval:function() {
    clearInterval(intervalId);
},

// 在页面逻辑部分定义 loadSong 方法
loadSong: function() {
  let that = this;
  let PlayingMid = that.data.MusicFromData[app.globalData.currentIndex].songmid;
  console.log(PlayingMid);
  let PlayingSong = that.data.MusicFromData[app.globalData.currentIndex];
  console.log(app.globalData.currentIndex);
  console.log(PlayingMid);

  // 设置音频管理器的开始时间
  app.globalData.backgroundAudioManager.startTime = that.data.currentTimeStamp;

  // 请求获取音乐播放 URL
  wx.request({
    url: 'http://localhost:3200/getMusicPlay?songmid=' + PlayingMid,
    success: function(data) {
      console.log(data);
      let playUrl = data.data.data.playUrl[PlayingMid].url;
      app.globalData.backgroundAudioManager.title = PlayingSong.songName;
      app.globalData.backgroundAudioManager.src = playUrl;
      app.globalData.backgroundAudioManager.onTimeUpdate(function () {
        const currentTime = app.globalData.backgroundAudioManager.currentTime;
        const isPaused = app.globalData.backgroundAudioManager.paused;
        const roomId = wx.getStorageSync('RoomId'); // 假设房间ID存储在缓存中
        const songId = PlayingMid; // 假设当前播放歌曲ID存储在PlayingMid中
    
        let currentLyric = '';
        for (let i = 0; i < that.data.lyrics.length; i++) {
            if (that.data.lyrics[i].time <= currentTime) {
                currentLyric = that.data.lyrics[i].text;
                console.log(currentLyric);
            } else {
                break;
            }
        }
    
        // 更新本地数据
        that.setData({
            currentLyric: currentLyric,
            curtime: Second(currentTime),
            durtime: Second(app.globalData.backgroundAudioManager.duration),
            jindu: currentTime / app.globalData.backgroundAudioManager.duration * 100,
            play_music: data.data.data.playUrl[PlayingMid].url,
            currentTimeStamp: currentTime
        });
        console.log(currentTime);
    });
    
    // 定时器，每2秒请求一次
    let intervalId = setInterval(() => {
        const currentTime = app.globalData.backgroundAudioManager.currentTime;
        const isPaused = app.globalData.backgroundAudioManager.paused;
        const roomId = wx.getStorageSync('RoomId'); // 假设房间ID存储在缓存中
        const songId = PlayingMid; // 假设当前播放歌曲ID存储在PlayingMid中
    
        if (!isPaused) {
          // 调用 RoomUpdateSongTime 接口更新歌曲状态
          wx.request({
              url: 'http://localhost:3000/RoomUpdateSongTime',
              method: 'POST',
              header: {
                  'content-type': 'application/json',
                  'Authorization': wx.getStorageSync('usertoken')
              },
              data: {
                  sid: songId,
                  rid: roomId,
                  nowtime: currentTime,
                  ispause: isPaused
              },
              success(res) {
                  if (res.statusCode === 207) {
                      console.log('更新歌曲状态成功');
                  } else if (res.statusCode === 257) {
                      console.error('更新歌曲状态失败', res.data);
                  } else if (res.data.code === 401) {
                      utils.userlogin();
                  } else if (res.statusCode === 200) {
                      console.log('信息传递成功', res);
                  } else {
                      console.error('请求失败，状态码:', res.statusCode);
                  }
              },
              fail(err) {
                  console.error('请求失败', err);
              }
          });
      }
  }, 2000);
  

      // 设置时间更新和结束事件监听器
      // app.globalData.backgroundAudioManager.onTimeUpdate(function () {
      //   const currentTime = app.globalData.backgroundAudioManager.currentTime;
      //   const isPaused = app.globalData.backgroundAudioManager.paused;
      //   const roomId = wx.getStorageSync('RoomId'); // 假设房间ID存储在缓存中
      //   const songId = PlayingMid; // 假设当前播放歌曲ID存储在PlayingMid中
      //   const songtime = wx.getStorageSync('currentTime')

      //   wx.setStorageSync('isPaused', isPaused);
      //   const ispaused = wx.getStorageSync('isPaused');
  

      //   // 更新本地数据
      //   that.setData({
      //       curtime: Second(currentTime),
      //       durtime: Second(app.globalData.backgroundAudioManager.duration),
      //       jindu: currentTime / app.globalData.backgroundAudioManager.duration * 100,
      //       play_music: data.data.data.playUrl[PlayingMid].url,
      //       currentTimeStamp: currentTime
      //   });
      //   console.log(currentTime);

      // //   if (ispaused) {
      // //     console.log('停止条件触发，停止发送请求');
      // //     return;
      // // }



      //   // 调用 RoomUpdateSongTime 接口更新歌曲状态
      //   wx.request({
      //       url: 'http://localhost:3000/RoomUpdateSongTime',
      //       method: 'POST',
      //       header: {
      //           'content-type': 'application/json',
      //           'Authorization': wx.getStorageSync('usertoken')
      //       },
      //       data: {
      //           sid: songId,
      //           rid: roomId,
      //           nowtime: currentTime,
      //           ispause: isPaused
      //       },
      //       success(res) {
      //           if (res.statusCode === 207) {
      //               console.log('更新歌曲状态成功');
      //           } else if (res.statusCode === 257) {
      //               console.error('更新歌曲状态失败', res.data);
      //           } else if (res.data.code === 401) {
      //               utils.userlogin();
      //           }else if(res.statusCode === 200){
      //             console.log('信息传递成功',res);
      //           } else {
      //               console.error('请求失败，状态码:', res.statusCode);
      //           }
      //       },
      //       fail(err) {
      //           console.error('请求失败', err);
      //       }
      //   });
      //   // that.getRoomSongTime();
      // });
      app.globalData.backgroundAudioManager.onEnded(function() {
        that.playNext();
      });
    }
  });

  // 请求获取专辑 MID
  wx.request({
    url: 'http://localhost:3200/getSongInfo?songmid=' + PlayingMid,
    success: function(data) {
      // console.log(data);
      that.setData({
        albumMid: data.data.response.songinfo.data.track_info.album.mid
      });
      // console.log(that.data.albumMid);
    }
  });

  // 请求获取歌词
  wx.request({
    url: 'http://localhost:3200/getLyric?songmid=' + PlayingMid,
    success: function (res) {
      // console.log(res);
      let lyricText = res.data.response.lyric;
      let lines = lyricText.split('\n');
      let lyrics = [];

      for (let line of lines) {
        let timeAndText = line.split(']');
        if (timeAndText.length >= 2) {
          let lyric = timeAndText[1].trim(); // 提取歌词内容部分
          lyrics.push(lyric);
        }
      }

      that.setData({
        lyrics: lyrics // 将处理后的歌词设置到数据中
      });
    },
  });

  let History = wx.getStorageSync('HistoryList') || [];
  if(History.filter(item => item.songmid === PlayingMid).length === 0) {
    History.push(PlayingSong);
    wx.setStorageSync('HistoryList', History);
  };


},


  // 在页面逻辑部分定义 togglePlay 方法
togglePlay: function () {
  let that = this;

  if (!that.data.isPlaying) { // 如果未播放，则开始播放
    app.globalData.backgroundAudioManager.play();
    that.setData({
      ImagePlay: '/static/播放.png',
      isPlaying: true,
    });
  } else { // 如果正在播放，则暂停
    app.globalData.backgroundAudioManager.pause();
    that.setData({
      ImagePlay: '/static/暂停.png',
      isPlaying: false,
    });
    this.stopUpdateInterval();
    wx.setStorageSync('isPaused', isPlaying)
  
    wx.setStorageSync('currentTime', that.data.currentTimeStamp);
  }
},


playNext: function() {
  let that = this;
  if (app.globalData.backgroundAudioManager.src) {
    app.globalData.backgroundAudioManager.stop();
  };
  let nowIndex = app.globalData.currentIndex;
  let MaxIndex = that.data.MusicFromData.length;
  if(nowIndex <= MaxIndex - 1) {
    nowIndex = nowIndex + 1;
    app.globalData.currentIndex++;
  } else {
    app.globalData.currentIndex = 0;
  };
  console.log(app.globalData.currentIndex);
  that.loadSong();
},

ToNextSong: function() {
  let that = this;
  if (app.globalData.backgroundAudioManager.src) {
    app.globalData.backgroundAudioManager.stop();
  };
  let nowIndex = app.globalData.currentIndex + 1;
  let MaxIndex = that.data.MusicFromData.length;
  if(nowIndex <= MaxIndex - 1) {
    app.globalData.currentIndex = nowIndex;
  } else {
    app.globalData.currentIndex = 0;
  };
  console.log(app.globalData.currentIndex);
  that.loadSong();
},


BackTo: function() {
  let that = this;
  if (app.globalData.backgroundAudioManager.src) {
    app.globalData.backgroundAudioManager.stop();
  };
  let nowIndex = app.globalData.currentIndex - 1;
  let MaxIndex = that.data.MusicFromData.length;
  let MinIndex = 0;
  if(nowIndex >= MinIndex) {
    app.globalData.currentIndex = nowIndex;
  } else {
    app.globalData.currentIndex = MaxIndex - 1;
  };
  console.log(app.globalData.currentIndex);
  that.loadSong();
},


searchMusic:function() {
  wx.navigateTo({
    url: '/pages/searchmusic/searchmusic',
  })
},
PlayListAdd:function(e) {
    let id = e.currentTarget.dataset.sId;
    let selectedSong = this.data.HistoryList.find(item => item.songMid === id);
    
    if (selectedSong) {
      if(!selectedSong.isAdded) {

        let AllsongsFromStorage = wx.getStorageSync('songs') || [];
        let selectedInAll = AllsongsFromStorage.find(item => item.songmid === songMid);
        selectedInAll.isAdded = true;
        wx.setStorageSync('songs', AllsongsFromStorage);
      
        let PlayList = wx.getStorageSync('MusicFromData');
        PlayList.push(selectedInAll);
        wx.setStorageSync('MusicFromData', PlayList);


        console.log("添加成功");
        wx.showToast({
          title: '添加成功',
          icon: 'success',
          duration: 1000
        });
      } else {
        console.log("歌曲已存在歌单中");
        wx.showToast({
          title:'请勿重复添加',
          icon: 'none',
          duration: 1000
        })
      }
    } 
  },


  LoadPlayList: function () {
    const roomId = wx.getStorageSync('RoomId'); 
    const that = this;

    // 调用 RoomGetSongs 接口获取房间的歌曲
    wx.request({
        url: 'http://localhost:3000/RoomGetSongs',
        method: 'GET',
        header: {
            'content-type': 'application/json',
            'Authorization': wx.getStorageSync('usertoken')
        },
        data: {
            rid: roomId
        },
        success(res) {
            console.log('正在获取房间歌曲');
            if (res.statusCode === 200) {
                console.log('获取房间歌曲成功', res.data);
                //将 songName, artist, songmid 存入 MusicFromData 数组
                const musicData = res.data.data.map(song => ({
                    songName: song.songName,
                    artist: song.songAuthor,
                    songmid: song.songId
                }));
                
                wx.setStorageSync('MusicFromData', musicData)
            } else if (res.data.code === 401) {
                utils.userlogin();
            } else {
                console.error('获取房间歌曲失败，状态码:', res.statusCode);
            }
        },
        fail(err) {
            console.error('请求失败', err);
        }
    });
    
}
,
  ClosePlayList: function () {
    this.setData({
      PlayListVisible: false
    });
  },


  MusicListReduce(e) {

    console.log(e.currentTarget.dataset.sId);
    let id = e.currentTarget.dataset.sId;
    console.log(id);
    let Music = wx.getStorageSync('MusicFromData');
    let newMusicFromData = Music.filter(item => item.songId !== id);
    wx.setStorageSync('MusicFromData', newMusicFromData);
    console.log("删除成功");
   
  },
  
  // LoveListChange(e) {
  //   let id = e.currentTarget.dataset.sId;
  //   utils.LovelistChange(id);
  //   console.log("改变收藏夹成功");
  // }, 
  
  
  // RoomGetSongTime(sid,rid)  get方法
  getRoomSongTime() {
    let sid = this.data.MusicFromData[app.globalData.currentIndex].songmid;
    console.log(sid);
    const rid = wx.getStorageSync('RoomId'); // 获取当前房间ID
    console.log(rid);
    if (!rid) {
      console.error('房间ID未找到');
      return;
    }
  
    wx.request({
      url: 'http://localhost:3000/RoomGetSongTime',
      method: 'GET',
      data: {
        sid: sid,
        rid: rid
      },
      header: {
        'content-type': 'application/json', // 根据需要设置
        'Authorization': wx.getStorageSync('usertoken')
      },
      success(res) {
        // console.log(res.data.code);
          console.log(res);
          let nowtime = res.data.data[0].nowsongtime;
          console.log(nowtime);
          let pau = res.data.data[0].ispause;
          wx.setStorageSync('currentTime', nowtime);

      },
      fail(err) {
        console.error('请求失败', err);
      }
    });
  }
})